package com.jz.community.basecomm.task;

import android.app.Activity;

import com.jz.community.basecomm.bean.LoginInfo;
import com.jz.community.basecomm.constant.Constant;
import com.jz.community.basecomm.net.OkHttpUtil;
import com.jz.community.basecomm.utils.BaseSpUtils;
import com.jz.community.basecomm.utils.JsonUtils;
import com.jz.community.basecomm.utils.Preconditions;
import com.jz.community.commview.view.widget.ProgressDialogManager;

import java.util.HashMap;

/**
 * Created by Tony.Fan on 2018/3/21 17:49
 */
public class GetSmsCodeTask extends RxTask<String, Integer, LoginInfo> {

    private Activity activity;
    private ITaskCallbackListener taskListener;
    private boolean isPhoneAlreadyExisting;

    public GetSmsCodeTask(Activity activity, boolean isPhoneAlreadyExisting,
                          ITaskCallbackListener taskListener) {
        super(activity);
        this.activity = activity;
        this.taskListener = taskListener;
        this.isPhoneAlreadyExisting = isPhoneAlreadyExisting;
    }

    @Override
    protected LoginInfo doInBackground(String... params) {
        // 执行请求
        String result;
        if ("1".equals(params[0])) {
            result = OkHttpUtil.post(Constant.SMS_LOGIN_CODE_URL, getParam(params[0], params[1]));
        } else {
            result = OkHttpUtil.get(Constant.SMS_CODE_URL + params[1] + "/" + isPhoneAlreadyExisting);
        }
        LoginInfo info = null;
        if (!Preconditions.isNullOrEmpty(result)) {
            info = JsonUtils.parseObject(result, LoginInfo.class);
            saveSmsCode(info);
        }
        return info;
    }

    @Override
    protected void onPostExecute(LoginInfo result) {
        // 执行结果回调函数
        taskListener.doTaskComplete(result);
        ProgressDialogManager.dismissProgressDialog();
        super.onPostExecute(result);
    }

    @Override
    protected void onPreExecute() {
        ProgressDialogManager.showDialog(activity);
        super.onPreExecute();
    }

    @Override
    protected void onCancelled() {
        super.onCancelled();
    }

    /**
     * 获取请求所需的参数
     *
     * @param
     * @return
     */
    private HashMap<String, Object> getParam(String codeType, String mobi) {
        HashMap<String, Object> map = new HashMap<>();
        if ("1".equals(codeType)) {
            map.put("username", mobi);
        }
        return map;
    }

    private void saveSmsCode(LoginInfo loginInfo) {
        if (!Preconditions.isNullOrEmpty(loginInfo.getVcode())) {
            BaseSpUtils.getInstance().setSmsCode(activity, loginInfo.getVcode());
        }
    }
}
